﻿#region Using namespaces

using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using AvalonDock;

#endregion

namespace BOL.Apps.GeneNetworkBrowser.Controls
{
    public partial class OutputPane : DockableContent
    {
        public OutputPane()
        {
            InitializeComponent();

            var tbsw = new TextBoxWriter(_tbOutput);

            Console.SetError(tbsw);
            Console.SetOut(tbsw);
        }

        internal class TextBoxWriter : TextWriter
        {
            TextBox _output = null;

            public override Encoding Encoding { get { return System.Text.Encoding.UTF8; } }

            public TextBoxWriter(TextBox output)
            {
                _output = output;
            }

            public override void Write(char value)
            {
                base.Write(value);
                _output.Dispatcher.BeginInvoke(new Action(() => { _output.AppendText(value.ToString()); }));
            }
        }

        private void _tbOutput_TextChanged(object sender, TextChangedEventArgs e)
        {
            _tbOutput.CaretIndex = _tbOutput.Text.Length;
            _tbOutput.ScrollToEnd();
            _tbOutput.Focus();
        }

        private void ClearAll(object sender, RoutedEventArgs e)
        {
            _tbOutput.Clear();
        }

        private void ToggleWordWrap(object sender, RoutedEventArgs e)
        {
            if (_tbOutput.TextWrapping == TextWrapping.NoWrap)
                _tbOutput.TextWrapping = TextWrapping.Wrap;
            else
                _tbOutput.TextWrapping = TextWrapping.NoWrap;
        }
    }
}
